﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using SpLocalizer.Common;
using SpLocalizer.Common.DbApi;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace SpLocalizer.ContentSourceProviders.SpTaxonomy
{
    public class SpTermSetContent : AbstractContent, IDisposable
    {

        private TermSet CurrentTermSet = null;
        private TaxonomySession session = null;

        internal static IEnumerable<AbstractContent> LoadAllFromTermStore(TermStore termstore)
        {
            List<AbstractContent> contentSources = new List<AbstractContent>();
            foreach (Group group in termstore.Groups)
            {
                foreach (TermSet termset in group.TermSets)
                {                    
                    SpTermSetContent content = new SpTermSetContent();
                    content.ContentId = termset.Id.ToString();
                    content.ContentTitle = termset.Name;
                    content.ContentAddress = termset.Group.Id.ToString();
                    content.CurrentTermSet = termset;
                    contentSources.Add(content);
                }
            }

            return contentSources;
        }


        internal void Bind(TaxonomySession session, string ContentId, String ContentTitle, string GroupId)
        {
            this.ContentId = ContentId;
            this.ContentTitle = ContentTitle;
            this.ContentAddress = GroupId;
            this.session = session;
        }


        public override IEnumerable<BaseTranslationTask> BuildTranslationTasks(CultureInfo FromLanguage, CultureInfo ToLanguage)
        {

            // Check if FromLanguage and ToLanguage are installed in the system

            if (!IsLanguageInstalled(FromLanguage)){
                throw new ApplicationException(String.Format("Source language {0} is not installed for the TermStore {1}. ", FromLanguage.Name, this.CurrentTermSet.TermStore.Name));
            }else{
                // Set language for current session
                this.CurrentTermSet.TermStore.WorkingLanguage = FromLanguage.LCID;
            }


            if (!IsLanguageInstalled(ToLanguage))
            {
                // If Destination language is not installed - try to enable it
                this.CurrentTermSet.TermStore.AddLanguage(ToLanguage.LCID);
            }

                List<BaseTranslationTask> tasksToTranslate = new List<BaseTranslationTask>();
                TermCollection terms = CurrentTermSet.Terms;
                foreach (Term term in terms)                
                    tasksToTranslate.AddRange(BuildTranslationTasks(FromLanguage, ToLanguage, term));
                
            return tasksToTranslate;

        }

        private IEnumerable<BaseTranslationTask> BuildTranslationTasks(CultureInfo FromLanguage, 
                                CultureInfo ToLanguage, Term theTerm){

            List<BaseTranslationTask> tasksToTranslate = new List<BaseTranslationTask>();
            SpTermLocalizationTask localizationTask = new SpTermLocalizationTask(FromLanguage, ToLanguage, theTerm);

            if (!String.IsNullOrEmpty(localizationTask.SourceText))
                tasksToTranslate.Add(localizationTask);

            if (theTerm.Terms.Count > 0)
            {
                foreach(Term term in  theTerm.Terms)
                    tasksToTranslate.AddRange(BuildTranslationTasks(FromLanguage, ToLanguage, term));
            }

            return tasksToTranslate;
        }


        /// <summary>
        /// Return true if language installed in the global language collection
        /// </summary>
        /// <param name="Language"></param>
        /// <returns></returns>
        private bool IsLanguageInstalled(System.Globalization.CultureInfo Language)
        {
            int LanguagesCount = this.CurrentTermSet.TermStore.Languages.Count<int>(lng => Language.LCID == lng);
            return LanguagesCount > 0;

        }


        public override void ExportContentTranslations(BaseTranslationTask TranslationTask)
        {

            if (!(TranslationTask is SpTermLocalizationTask))
                 throw new ArgumentException(String.Format("Illegal type {0} for translation task id {1}",
                    TranslationTask.GetType().ToString(), TranslationTask.TaskId));


            Term theTerm =  this.session.GetTerm(((SpTermLocalizationTask)TranslationTask).TermId);
            ((SpTermLocalizationTask)TranslationTask).UpdateLabel(theTerm);

        }

        public override void PerformExportDone()
        {
            
        }

        public void Dispose()
        {
            if (this.CurrentTermSet != null)
            {
                this.CurrentTermSet = null;
            }
        }
    }
}
